# -*- coding: utf-8 -*-
# @Time    : 2018/2/18 12:57
# @Author  : Soft
# @File    : TimedTask.py
# @Desc    : 定时任务 用来自动调整课程状态
import logging

from module.TimeUtils import get_class_status, get_time
from module.class_.service import ClzService
from module.user.service import StuService
from module.record.service import ReService
from module.work.service import WorkService
from module.models import Class
from module.cache import cache

log = logging.getLogger()

fmt = '%Y-%m-%d %H:%M'
class_status_val = ['未开始', '进行中', '已结束']


# 自动更新课程状态
def flush_class_status():
    clz_list = Class.select().where(Class.k_status <= 1)
    if len(clz_list):
        for clz in clz_list:
            try:
                k_time = str(clz.k_time)
                work_end_time = str(clz.k_work_endtime)
                status = get_class_status(k_time, work_end_time)
                if clz.k_status != status:
                    k_name = clz.k_name.encode('utf-8')
                    if Class.update(k_status=status).where(Class.id == clz.id).execute():
                        log.info('更新课程状态成功--> %s %s' % (k_name, class_status_val[status]))
                    else:
                        log.warn('更新课程状态失败--> %s' % k_name)
            except BaseException as e:
                log.debug('更新课程状态异常--> %s' % e)
    else:
        log.info('无课程需要更新状态')


# 自动更新签到记录 添加旷课的学生记录
def flush_record():
    now_class = ClzService.get_now_clazz()
    if now_class:
        year = now_class.get('k_time')[:4]
        kid = now_class.get('id')
        students = list(StuService.by_year(year))
        students.pop(0)
        for stu in students:
            sid = int(stu.get('id'))
            if not ReService.is_has(kid=kid, sid=sid)[0]:
                ReService.add(k_id=kid, stu_id=sid, rd_time=get_time(), rd_status=0)
                log.info('添加旷课学生成功--> %s' % stu.get('stu_name').encode('utf-8'))
    else:
        log.info('无课程需要更新签到记')


# 自动更新交作业记录 添加没有交作业的学生
def flush_work():
    try:
        prev_class = Class.select().where(Class.k_work_endtime < get_time()). \
            order_by(Class.k_time.desc()).get().to_dict()
        year = prev_class.get('k_time')[:4]
        kid = prev_class.get('id')
        students = list(StuService.by_year(year))
        students.pop(0)
        for stu in students:
            sid = int(stu.get('id'))
            if not WorkService.is_has(sid=sid, kid=kid)[0]:
                WorkService.add(k_id=kid, stu_id=sid, work_status=0,
                                work_score=0, work_uptime=get_time(), work_url='')
                log.info('添加未交作业记录成功--> %s' % stu.get('stu_name').encode('utf-8'))
    except BaseException as e:
        log.info('无已完成课程需要更新作业记录--> %s' % e)


def clear_cache():
    try:
        cache.clear()
    except BaseException as e:
        log.warn('没有缓存')


flush_record()
